#include <iostream>
#include <mysql/mysql.h>
#include <string>
#include <unistd.h>

const std::string host = "localhost";
const std::string user="connentor";
const std::string password = "123456";
const std::string db = "conn";
const unsigned int port = 3306;

int main(){
    std::cout<<"mysql version: "<<mysql_get_client_info()<<std::endl;
    MYSQL* my = mysql_init(nullptr);
    if(nullptr == my){
        std::cerr << "init Mysql error"<<std::endl;
    }

    if(mysql_real_connect(my,host.c_str(),user.c_str(),password.c_str(),db.c_str(),port,nullptr,0) == nullptr) {
        std::cerr << "connect MYSQL error" << std::endl;
        return 2;
    }
    std::cout<<"connect success" <<std::endl;
    mysql_set_character_set(my,"utf8");
    //std::string sql = "select name,age from user where id = 3";
    std::string sql = "select * from user";
    //sql="insert into user values ('3','林颖',25,52352423)";
    int n = mysql_query(my,sql.c_str());
    if(n == 0) std::cout << "sql success " << std::endl;
    else {
        std::cerr<<"sql fail" << std::endl; 
        return 3;
    }

    MYSQL_RES* res = mysql_store_result(my);
    if(res == nullptr){
        std::cerr<<"mysql_store_result_error" << std::endl;
        return 4;
    }

    int rows = mysql_num_rows(res);
    int fields = mysql_num_fields(res);
    
    std::cout<<"行 " << rows << std::endl;
    std::cout<<"列 " << fields << std::endl;

    MYSQL_FIELD *fields_array =mysql_fetch_field(res);
    for(int j = 0; j < fields; j++){
        std::cout << fields_array[j].name << "\t";
    }
    std::cout<<std::endl;

    //内容
    for(int i = 0; i < rows; i++){
        MYSQL_ROW row = mysql_fetch_row(res);
        for(int j = 0; j < fields; j++){
            std::cout << row[j] << "\t" ;
        }
        std::cout << "\n";
    }

    //sleep(10);
    // std::string sql;
    // while(true){
    //     std::cout<<"MySQL>>>";
    //     if(!std::getline(std::cin,sql)) break;
    //     if(sql == "quit") {
    //         std::cout<<"Bye"<<std::endl;
    //         break;
    //     }
    //     int n = mysql_query(my,sql.c_str());
    //     if(n==0){
    //         std::cout<<sql << " suceess "<<n<<std::endl;
    //     }else{
    //         std::cerr<<sql<<" failed "<<n<<std::endl;
    //     }
    // }

    mysql_free_result(res);
    mysql_close(my);
    return 0;
}